#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
主题: 合并拼接字符串
问题: 你想将几个小的字符串合并为一个大的字符串
提示:
"""


def recipe1():
    """合并的字符串是在一个序列或者 iterable 中"""
    parts = ['Is', 'Chicago', 'Not', 'Chicago?']
    print(f"{parts = }")
    print(f"{' '.join(parts) = }")
    print(f"{','.join(parts) = }")
    print(f"{''.join(parts) = }")


def recipe2():
    """合并少数几个字符串，使用加号(+)通常已经足够了"""
    a = 'Is Chicago'
    b = 'Not Chicago?'
    print(f"{a = }")
    print(f"{b = }")
    print(f"{a + ' ' + b = }")

    # 替代方案
    print(f"{'{} {}'.format(a, b) = }")


def recipe3():
    """源码中将两个字面字符串合并起来"""
    a = 'Hello' 'World' # NOSONAR
    print(f"{a = }")


def recipe4():
    """相对比较聪明的技巧是利用生成器表达式"""
    data = ['ACME', 50, 91.1]
    a = ','.join(str(d) for d in data)
    print(f"{a = }")


def recipe5():
    """注意不必要的字符串连接操作"""
    a = 'a'
    b = 'b'
    c = 'c'
    print(f"{a + ':' + b + ':' + c = }")  # Ugly
    print(f"{':'.join([a, b, c]) = }")  # Still ugly
    print(a, b, c, sep=':')  # Better

def recipe6():
    """如果你准备编写构建大量小字符串的输出代码， 你最好考虑下使用生成器函数"""
    a = ''.join(sample())
    print(f"{a= }")

    for part in sample():
        print(f"{part= }")

def recipe7():
    """一些结合I/O操作的混合方案"""
    maxsize = 32678
    for part in combine(sample(), maxsize):
        print(f"{part= }")

    with open('./14_join_str.txt', 'w') as f:
        for part in combine(sample(), maxsize):
            f.write(part)

def combine(source, maxsize):
    parts = []
    size = 0
    for part in source:
        parts.append(part)
        size += len(part)
        if (size > maxsize):
            yield ''.join(parts)
            parts = []
            size = 0
    yield ''.join(parts)

def sample():
    yield 'Is'
    yield 'Chicago'
    yield 'Not'
    yield 'Chicago?'

def main():
    print('recipe1'.center(20, '*'))
    recipe1()
    print('recipe2'.center(20, '*'))
    recipe2()
    print('recipe3'.center(20, '*'))
    recipe3()
    print('recipe4'.center(20, '*'))
    recipe4()
    print('recipe5'.center(20, '*'))
    recipe5()
    print('recipe6'.center(20, '*'))
    recipe6()
    print('recipe7'.center(20, '*'))
    recipe7()

if __name__ == '__main__':
    main()     